const express=require('express')
const cors=require('cors')
const joi=require('joi')
var bodyParser = require('body-parser');


 const app=express()
 app.use(cors())
 
 app.use(bodyParser.json({limit: '20mb'}));//使能 post 50mb以下的数据
app.use(bodyParser.urlencoded({limit: '20mb', extended: true}));


app.use(express.urlencoded({extended:false}))

  //定义错位中间件，res.cc
  app.use((req,res,next)=>{
      res.cc=function(err,status=400){
        res.send({
            status,
            msg:err instanceof Error ? err.massage : err
        })
      }
      next()
  })


const expressJWT=require('express-jwt')
const config=require('./config')

app.use(expressJWT({secret:config.jwtSecretKey}).unless({path:[/^\/api/]}))

const userRouter=require('./router/user')
app.use('/api',userRouter)

const userinfoRouter=require('./router/userinfo')
app.use('/my',userinfoRouter)

const artCateRouter=require('./router/artcate')
app.use('/my/article',artCateRouter)

const articleRouter=require('./router/article')
app.use('/my/article',articleRouter)




//定义错误级别中间件,这是一定要放在最后的
app.use((err,req,res,next)=>{
    if(err instanceof joi.ValidationError) return res.cc(err.toString())//这里err格式有问题，转成字符串就好了
    if(err.name==='UnauthorizedError') return res.cc('身份认证失败')
    res.cc(err.massage)
})

 app.listen(3007,()=>{
     console.log('api server running at http://127.0.0.1:3007');
 })